package 所有的题类.ZA.链表;

import com.kiwi.nixu.common.LNode;

import javax.xml.stream.FactoryConfigurationError;
import java.util.Arrays;
import java.util.List;

public class 交换链表中的节点 {
    public static LNode arrayToLNode(List<Integer> list){
        LNode lNode = new LNode(list.get(0));
        LNode cur=lNode;
        for (int i = 1; i < list.size(); i++) {
            LNode tmp=new LNode(list.get(i));
            cur.next=tmp;
            cur=tmp;
        }
        return lNode;
    }
    public static void main(String[] args) {
        LNode lNode = arrayToLNode(Arrays.asList(1,2));
        LNode lNode1 = swapNodes(lNode, 1);
        System.out.println(lNode1.data);
    }
    public static LNode swapNodes(LNode head, int k) {
        //头结点
        LNode p=head;

        LNode n1=sortKNode(head,k);

        //倒序第k个节点
        LNode n2=reserSortKNode(head,k);

        int num=n1.data;
        n1.data=n2.data;
        n2.data=num;
        return p;
    }

    /*
     *正序目标节点的前一个节点
     */
    public static LNode sortKPreNode(LNode head,int k){
        if(k==1){
            return null;
        }
        while((k-2)>0){
            head=head.next;
            k--;
        }
        return head;
    }

    /*
     *正序目标节点的前一个节点
     */
    public static LNode sortKNode(LNode head,int k){
        while((k-1)>0){
            head=head.next;
            k--;
        }
        return head;
    }

    /*
     *倒序目标节点的前一个节点
     */
    public static LNode reserSortKPreNode(LNode head,int k){
        LNode fast=head;
        while ((k+1)>0 && fast!=null){
            fast=fast.next;
            k--;
        }
        if(fast==null){
            return null;
        }
        LNode slow=head;
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }

    public static LNode reserSortKNode(LNode head,int k){
        LNode fast=head;
        while ((k)>0){
            fast=fast.next;
            k--;
        }
        LNode slow=head;
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }
}
